package com.vlin.listener;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

import com.vlin.config.email.EmailProperties;

@Component
public class EurekaStateChangeListener {

	@Autowired
	private RedisTemplate<String, String> template;
	
	@Autowired
	private MailSender mailSender;
	
	@Autowired
	private EmailProperties emailProperties;
	
	

	@EventListener
	public void listen(final EurekaInstanceCanceledEvent event) {
		String serviceId = event.getServerId() + event.getAppName();
		final byte[] key = serviceId.getBytes(Charset.forName("UTF-8"));
		boolean exst = template.execute(new RedisCallback<Boolean>() {

			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				// connection.get(event.getServerId().getBytes(Charset.forName("UTF-8")));

				return connection.exists(key);
			}

		});
		String message = String.format("%s  %s 服务下线", event.getServerId(), event.getAppName());
		if (!exst) {
			template.opsForValue().set(serviceId, message, 60 * 3, TimeUnit.SECONDS);
			SimpleMailMessage msg = new SimpleMailMessage();
			msg.setFrom(emailProperties.getUsername());
			msg.setTo("136045210@qq.com");
			msg.setSubject(serviceId);
			msg.setText(message);
			mailSender.send(msg);
		}

		System.err.println(event.getServerId() + "\t" + event.getAppName() + " 服务下线");
	}

	@EventListener
	public void listen(EurekaInstanceRegisteredEvent event) {
		// InstanceInfo instanceInfo = event.getInstanceInfo();
		// instanceInfo.
		// System.err.println(instanceInfo.getAppName() + "进行注册");
	}

	@EventListener
	public void listen(EurekaInstanceRenewedEvent event) {
		// System.err.println(event.getServerId() + "\t" + event.getAppName() + "
		// 服务进行续约");
	}

	@EventListener
	public void listen(EurekaRegistryAvailableEvent event) {
		// System.err.println("注册中心 启动");
	}

	@EventListener
	public void listen(EurekaServerStartedEvent event) {
		// System.err.println("Eureka Server 启动");
	}

}
